package com.bnlr.lrparking.appui.approve;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.constant.LrConstant;
import com.bumptech.glide.Glide;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.util.BitmapHelper;
import com.bnlr.lrparking.util.FileUtil;
import com.bnlr.lrparking.model.UpImgM;
import com.bnlr.lrparking.model.UploadGoodsBean;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.util.LimitEditText;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;
import com.zzti.fengyongge.imagepicker.PhotoSelectorActivity;
import com.zzti.fengyongge.imagepicker.model.PhotoModel;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created by hp on 2017/9/1.
 * 实名认证
 */
public class ApproveActivity extends BaseActivity {

    private TextView tvNavTitle;
    private RelativeLayout rely_man,rely_woman;
    private CheckedTextView check_man,check_woman;
    private LimitEditText ed_approve_name;
    private EditText ed_voucher;
    private ClearEditText ed_approve_code;
    private OptionsPickerView pvCustomOptions;
    private TextView tv_approve_btn;
    private ArrayList<String> voucherType = new ArrayList<>();
    private String approve_name="",approve_voucher="",approve_code="";
    private ImageView img_ID_card1,img_ID_card2;

    private List<PhotoModel> single_photos = new ArrayList<PhotoModel>();
    private ArrayList<UploadGoodsBean> img_uri = new ArrayList<UploadGoodsBean>();
    private String BackImg="",ForeImg="";
    private  Intent intent;
    private int approve_type;
    private String sex="0";
    private static final String PASS_PORT = "^1[45][0-9]{7}|([P|p|S|s]\\d{7})|([S|s|G|g]\\d{8})|([Gg|Tt|Ss|Ll|Qq|Dd|Aa|Ff]\\d{8})|([H|h|M|m]\\d{8,10})$";
    private static final String HKMAKAO = "^[HMhm]{1}([0-9]{10}|[0-9]{8})$";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_approve);
        initView();
    }

    private void initView(){
        voucherType.add("二代身份证");
        voucherType.add("护照");
        voucherType.add("港澳通行证");
        initCustomOptionPicker();
        tvNavTitle=(TextView)findViewById(R.id.tv_nav_title);
        tvNavTitle.setText("身份信息");
        rely_man=(RelativeLayout)findViewById(R.id.rely_man);
        rely_woman=(RelativeLayout)findViewById(R.id.rely_woman);
        check_man=(CheckedTextView)findViewById(R.id.check_man);
        check_woman=(CheckedTextView)findViewById(R.id.check_woman);
        ed_voucher=(EditText)findViewById(R.id.ed_voucher);
        ed_approve_name=(LimitEditText)findViewById(R.id.ed_approve_name);
        ed_approve_code=(ClearEditText)findViewById(R.id.ed_approve_code);
        tv_approve_btn=(TextView)findViewById(R.id.tv_approve_btn);
        img_ID_card1=(ImageView)findViewById(R.id.img_ID_card1);
        img_ID_card2=(ImageView)findViewById(R.id.img_ID_card2);
        rely_man.setOnClickListener(this);
        rely_woman.setOnClickListener(this);
        ed_voucher.setOnClickListener(this);
        ed_approve_name.addTextChangedListener(this);
//        ed_voucher.addTextChangedListener(this);
        ed_approve_code.addTextChangedListener(this);
        tv_approve_btn.setOnClickListener(this);
        img_ID_card1.setOnClickListener(this);
        img_ID_card2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.rely_man:
                sex="0";
                check_man.setChecked(false);
                check_woman.setChecked(true);
                break;
            case R.id.rely_woman:
                sex="1";
                check_man.setChecked(true);
                check_woman.setChecked(false);
                break;
            case R.id.ed_voucher:
                pvCustomOptions.show();
                break;
            case R.id.img_ID_card1:
                intent = new Intent(ApproveActivity.this, PhotoSelectorActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent.putExtra("limit",1);
                startActivityForResult(intent, 0);
                break;
            case R.id.img_ID_card2:
                Intent intent1 = new Intent(ApproveActivity.this, PhotoSelectorActivity.class);
                intent1.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                intent1.putExtra("limit",1);
                startActivityForResult(intent1,1);
                break;
            default:
                break;
        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        super.afterTextChanged(s);
        approve_name=ed_approve_name.getText().toString();
        approve_voucher=ed_voucher.getText().toString();
        approve_code=ed_approve_code.getText().toString();

        if (!approve_name.equals("")&&!approve_voucher.equals("")&&!approve_code.equals("") && approve_code.length() > 0){
            tv_approve_btn.setBackgroundResource(R.drawable.seletor_login_btn);
            tv_approve_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (BackImg.equals("") || ForeImg.equals("")) {
                        ToastUtils.showShort("请上传完相关图片");
                        return;
                    }
                    if (approve_name.length() < 2) {
                        ToastUtils.showShort("请输入正确的姓名");
                        return;
                    }
                    switch (approve_type) {
                        case 0:
                            if (!RegexUtils.isIDCard15(approve_code) && !RegexUtils.isIDCard18(approve_code)) {
                                ToastUtils.showShort("请输入正确的身份证号");
                                return;
                            }
                            break;
                        case 2:
                            if (!Pattern.matches(PASS_PORT, approve_code)) {
                                ToastUtils.showShort("请输入正确的护照号码");
                                return;
                            }
                            break;
                        case 3:
                            if (!Pattern.matches(HKMAKAO, approve_code)) {
                                ToastUtils.showShort("请输入正确的港澳通行证");
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    tv_approve_btn.setEnabled(false);
                    sendInformation(BackImg,ForeImg);
                }
            });
        }else {
            tv_approve_btn.setBackgroundResource(R.mipmap.login_disabled);
            tv_approve_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    CommonUtil.showToask(baseContext,"请检查信息是否完整？");
                }
            });
        }
    }

    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = voucherType.get(options1).toString();
                ed_voucher.setText(tx);
                switch (options1) {
                    case 0:
                        approve_type=0;
                        break;
                    case 1:
                        approve_type=2;
                        break;
                    case 2:
                        approve_type=3;
                        break;
                    default:
                        break;
                }

            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(voucherType);//添加数据
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 0:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (!FileUtil.fileExists(paths.get(0))) {
                        return;
                    }
                    Glide.with(this).load(paths.get(0)).into(img_ID_card1);
                    BackImg=CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(0), 200));
                }
                break;
            case 1:
                if (data != null) {
                    List<String> paths = (List<String>) data.getExtras().getSerializable("photos");
                    if (!FileUtil.fileExists(paths.get(0))) {
                        return;
                    }
                    Glide.with(this).load(paths.get(0)).into(img_ID_card2);
                    ForeImg = CommonUtil.bitmapToBase64(BitmapHelper.getImage(paths.get(0), 200));
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //提交身份验证
    private void sendInformation(String BackImg, String ForeImg){
        try {
            mRequest = NoHttp.createStringRequest(Urls.NEW_IP, LrConstant.POST);
            
            mRequest.add("action", "IdentityAuth");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("RealName", approve_name);
            mRequest.add("Sex", sex);//用户性别，0男，1女
            mRequest.add("IdCard",approve_code);//证件号码
            mRequest.add("CardType",approve_type);//证件类型，卡片类型，0身份证，1驾驶证，2护照，3港澳通行证
            mRequest.add("BackImg",BackImg);//证件背面图片
            mRequest.add("ForeImg",ForeImg);//证件正面图片


            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<UpImgM>(baseContext, true, null) {
                        @Override
                        public void doWork(UpImgM data, String code) {
                            if (TextUtils.equals("1", code)) {
                            } else {
                                CommonUtil.showToask(baseContext, "0");
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (TextUtils.equals("1", code)) {
                                    AppConfig.getInstance().putString("isRealNameAuth", "2");
                            /*      AppConfig.getInstance().putString("isRealNameAuth", "2");//实名认证状态，0未认证，
                                    AppConfig.getInstance().putString("approve_name", approve_name);//实名认证名
                                    AppConfig.getInstance().putString("sex", sex);//性别
                                    AppConfig.getInstance().putString("approve_type", approve_type+"");//证件类型
                                    AppConfig.getInstance().putString("approve_code", approve_code);//证件号*/
                                    finish();//关闭当前界面
                                } else {
                                    tv_approve_btn.setEnabled(true);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
}
